﻿using System;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using Business;
using DataAccess.i2iPortalTableAdapters;

public partial class admin_OilReport_Mangage : System.Web.UI.Page
{
    private int componentid;
	private string surveydate;
	private string formatedDateString;
    private String componentname;
    private string machinename;
    private string[] componentIDS;
    private ComponentsOnMachinesTableAdapter adapter = new ComponentsOnMachinesTableAdapter();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["componentID"] != null)
        {
            label_choose.Visible = false;
            componentname = (String) Request.QueryString["componentname"];
            componentid = Int32.Parse((String) Request.QueryString["componentID"]);
            machinename = (String) Request.QueryString["machinename"];
            component_label.Text = machinename + "-->" + componentname;
            component_label.Attributes["fontcolor"] = "RED";
            component_label.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            label_choose.Visible = true;
            component_label.Attributes["fontcolor"] = "RED";
            component_label.ForeColor = System.Drawing.Color.Red;
        }
        componentIDS = (String[])Session["componentIDs"];
        surveydate = (string) Session["SurveyDate"];
    	DateTime surveyDate = Convert.ToDateTime(surveydate);
		formatedDateString = HelperClass.GetStringFromDate(surveyDate);
		Date_label.Text = formatedDateString;

        LoadReports();
    }

    protected void AddButton_Click(object sender, EventArgs e)
    {
        string sampleID = SampleID_tb.Text;
        if (sampleID != "")
        {
            InsertSample(sampleID, componentid, surveydate);
        }
        else
        {
            ErrMsg_lb.Text = "Please Input SampleNo.";
        }
        LoadReports();
    }

    protected void InsertSample(string sampleID, int componentid, string datesampled)
    {
        try
        {
            string verify_query = "SELECT Value FROM ComponentTechnicalData WHERE Component_id='" + componentid +
                                  "' and (Attribute='uin' or Attribute='UIN')";
            CreateConn objct = new CreateConn();
            DataTable dt2 = objct.SQLConnDataTable(verify_query);
            if (dt2 != null && dt2.Rows.Count > 0)
            {
                ErrMsg_lb.Text = "Already has UIN/Sample No on this component!";
                return;
            }
            ErrMsg_lb.Text = "";
            string query_insert = "INSERT INTO ComponentTechnicalData(Component_id,Attribute,Value) values"
                                  + "('" + componentid + "','uin','" + sampleID + "')";
            CreateConn objconn_insert = new CreateConn();
            objconn_insert.SQLConnDataTable(query_insert);
        }
        catch (Exception e)
        {
            ErrMsg_lb.Text = e.ToString();
        }
    }

    protected void LoadReports()
    {
        tb_report.Rows.Clear();
        var headerName = new TableCell();
        headerName.Text = "Name";
        var head_0 = new TableCell();
        head_0.Text = "UIN/Sample No";
        var head_1 = new TableCell();
        head_1.Text = "SampleSent";
        var head_2 = new TableCell();
        head_2.Text = "DateSampled";
        var head_3 = new TableCell();
        head_3.Text = "Result";
        var head_4 = new TableCell();
        head_4.Text = "ReportDownload";
        var header = new TableRow();
        header.Cells.Add(headerName);
        header.Cells.Add(head_0);
        header.Cells.Add(head_1);
        header.Cells.Add(head_2);
        header.Cells.Add(head_3);
        header.Cells.Add(head_4);
        tb_report.Rows.Add(header);
        string query = "SELECT * FROM ComponentTechnicalData WHERE Attribute='uin' or Attribute='UIN'"
                       + " and Value is not null";
        var dt = new DataTable();
        var objconn = new CreateConn();
        try
        {
            dt = objconn.SQLConnDataTable(query);
        }
        catch (Exception e)
        {
            ErrMsg_lb.Text = e.ToString();
        }
        int checkbox_index = 0;
        if (dt != null && dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                string componentID = dr["Component_id"].ToString();
                if (componentIDS.Contains(componentID))
                {
                    string UIN = dr["Value"].ToString();
                    string query2 = "SELECT * FROM  OilReports WHERE Component_id='" + Int32.Parse(componentID) +
                                    "' and tested_date=convert(datetime,'" + surveydate + "',103)";
                    CreateConn objconn2 = new CreateConn();
                    DataTable dt_samples = objconn2.SQLConnDataTable(query2);

                    if (dt_samples.Rows != null && dt_samples.Rows.Count > 0)
                    {
                        foreach (DataRow dr_sample in dt_samples.Rows)
                        {
                            string status = dr_sample["status"].ToString();
                            string reportlink2 = dr_sample["reportlink"].ToString();
                            TableCell tc_link = new TableCell();
                            TableCell tc_result = new TableCell();
                            tc_result.Text = status == "" ? "N/A" : status;

                            if (reportlink2.Equals("") || reportlink2 == null)
                            {
                                reportlink2 = "N/A";
                                tc_link.Text = reportlink2;
                            }
                            else
                            {
                                reportlink2 = "../Mails/" + dr_sample["reportlink"].ToString();
                                tc_link.Text = "<a href='" + reportlink2 + "' target=_blank>Download";
                            }
                            string id = UIN;
                            TableRow tr = new TableRow();
                            TableCell tc_id = new TableCell();
                            tc_id.Text = id;
                            
                            TableCell tc_Name = new TableCell();
                            var components = adapter.GetComponentDetailByID(Int32.Parse(dr_sample["component_id"].ToString()));
                            if (components == null || components.Rows.Count == 0)
                            {
                                continue;
                            }
                            tc_Name.Text =  components.Rows[0]["machineName"].ToString() + "-"+components.Rows[0]["componentName"].ToString();
                            TableCell tc_status = new TableCell();
                            CheckBox cb_status = new CheckBox();

                            cb_status.ID = "cb_status" + checkbox_index.ToString();

                            cb_status.Checked = true;

                            TableCell tc_date = new TableCell();
                            tc_date.Text = formatedDateString;

                            tc_status.Controls.Add(cb_status);

                            tr.Cells.Add(tc_Name);
                            tr.Cells.Add(tc_id);
                            tr.Cells.Add(tc_status);
                            tr.Cells.Add(tc_date);
                            tr.Cells.Add(tc_result);
                            tr.Cells.Add(tc_link);
                            var tc_hidden_componentID = new TableCell();
                            var cptID = new HiddenField();
                            cptID.Value = componentID;
                            cptID.ID = "hidden" + checkbox_index;
                            tc_hidden_componentID.Controls.Add(cptID);
                            tr.Cells.Add(tc_hidden_componentID);
                            tb_report.Rows.Add(tr);
                            checkbox_index = checkbox_index + 1;
                        }
                    }
                    else
                    {
                        string testeddate = "N/A";
                        string id = UIN;
                        TableRow tr = new TableRow();
                        TableCell tc_id = new TableCell();
                        tc_id.Text = id;

                        var tc_Name = new TableCell();
                        var components = adapter.GetComponentDetailByID(Int32.Parse(dr["component_id"].ToString()));
                        if (components == null || components.Rows.Count == 0)
                        {
                            continue;
                        }
                        tc_Name.Text =  components.Rows[0]["machineName"].ToString() + "-"+ components.Rows[0]["componentName"].ToString();
                        TableCell tc_status = new TableCell();
                        CheckBox cb_status = new CheckBox();
                        cb_status.Checked = false;
                        cb_status.ID = "cb_status" + checkbox_index;

                        TableCell tc_date = new TableCell();
                        tc_date.Text = testeddate;
                        TableCell tc_result = new TableCell();
                        tc_result.Text = "N/A";
                        tc_status.Controls.Add(cb_status);
                        tr.Cells.Add(tc_Name);
                        tr.Cells.Add(tc_id);
                        tr.Cells.Add(tc_status);
                        tr.Cells.Add(tc_date);
                        tr.Cells.Add(tc_result);
                        var tc_link = new TableCell();
                        tc_link.Text = "N/A";
                        tr.Cells.Add(tc_link);
                        var tc_hidden_componentID = new TableCell();
                        var cptID = new HiddenField();
                        cptID.ID = "hidden" + checkbox_index;
                        cptID.Value = componentID;
                        tc_hidden_componentID.Controls.Add(cptID);
                        tr.Cells.Add(tc_hidden_componentID);
                        tb_report.Rows.Add(tr);
                        checkbox_index = checkbox_index + 1;
                    }
                }
            }
        }
    }

    protected void UpdateButton_Click(object sender, EventArgs e)
    {
        if (tb_report.Rows.Count > 0)
        {
            int checkbox_index = 0;
            foreach (TableRow  tr in tb_report.Rows)
            {
                TableCell tc = tr.Cells[2];
                if (tr.Cells[1].Text.Equals("UIN/Sample No"))
                    continue;
                CheckBox cb = (CheckBox) tc.FindControl("cb_status" + checkbox_index.ToString());
                if (cb == null)
                {
                    continue;
                }
                bool check_status = cb.Checked;

                if (check_status)
                {
                    TableCell tc_date = tr.Cells[3];
                    if (tc_date.Text.Equals("N/A"))
                    {
                        TableCell tc_id = tr.Cells[6];
                        HiddenField hiddenID = (HiddenField) tc_id.FindControl("hidden" + checkbox_index.ToString());
                        string componentID = hiddenID.Value;
                    	tc_date.Text = formatedDateString;


                        string query = "INSERT INTO OilReports(Component_id,tested_date) values ('" + componentID + "'"
                                       + ",convert(datetime,'" + surveydate + "',103))";
                        CreateConn objconn = new CreateConn();
                        try
                        {
                            objconn.SQLConnDataTable(query);
                        }
                        catch (Exception err)
                        {
                            ErrMsg_lb.Text = err.ToString();
                        }
                    }
                }
                else
                {
					TableCell tc_date = tr.Cells[3];
                    if (tc_date.Text.Equals("N/A"))
                    {
                    	continue;
                    }
                    TableCell tc_id = tr.Cells[6];
                    HiddenField hiddenID = (HiddenField) tc_id.FindControl("hidden" + checkbox_index.ToString());

                    string componentID = hiddenID.Value;
                    string query_select = "Delete FROM OilReports WHERE Component_id='" + componentID +
                                          "' and tested_date= convert(datetime,'" + tc_date.Text + "',103)";
                    CreateConn objc3 = new CreateConn();
                    try
                    {
                        objc3.SQLConnDataTable(query_select);
                    }
                    catch (Exception err)
                    {
                        ErrMsg_lb.Text = err.ToString();
                    }
                }
                checkbox_index++;
            }
               Response.Redirect(Request.RawUrl);
        }
    }

    protected void SendButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("EmailNotification.aspx");
    }

    protected void CHECKBUTTON_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Default.aspx");
    }

	protected void cbSelectAll_CheckedChanged(object sender, EventArgs e)
	{
		bool selectAll = cbSelectAll.Checked;
		foreach (TableRow row in tb_report.Rows)
		{
			foreach (TableCell cell in row.Cells)
			{
				foreach (var control in cell.Controls)
				{
					if (control is CheckBox)
					{
						var checkBox = control as CheckBox;
						checkBox.Checked = selectAll;
						break;
					}
				}
			}
		}
	}
}

